package com.xq.kotlin.coroutines

import kotlinx.coroutines.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext

/**
 * @author jltxseo
 *         Created by junlintianxia on 2019/12/19.
 */
fun main() = runBlocking {
    println("runBlocking : working in thread ${Thread.currentThread().name}")

    var ceshi = async(Dispatchers.Default) {
        println("async io1 ${Thread.currentThread()}")
        "async io1"
    }
    println("async的值 ${ceshi.await()} ${Thread.currentThread()}")
    globalScopeUse()
}

//使用 GlobalScope 单例对象
//可以直接调用 launch 开启协程
fun globalScopeUse() {
    val interceptor = object : ContinuationInterceptor{
        override val key: CoroutineContext.Key<*>
            get() = ContinuationInterceptor

        override fun <Any> interceptContinuation(continuation: Continuation<Any>): Continuation<Any> {
            return object : Continuation<Any>{
                override val context: CoroutineContext
                    get() = continuation.context

                override fun resumeWith(result: Result<Any>) {
                    println("GlobalScope : resumeWith ${Thread.currentThread().name} ${result.isSuccess} ${result.getOrNull()}")
                    continuation.resumeWith(result)
                }

            }
        }

    }

    GlobalScope.launch(Dispatchers.IO + interceptor) {
        println("GlobalScope : working in thread ${Thread.currentThread().name}")
    }
}

//通过 CoroutineContext 创建一个 CoroutineScope 对象
fun customCoroutineScope() {
    //自行通过 CoroutineContext 创建一个 CoroutineScope 对象
    //需要一个类型为 CoroutineContext 的参数
    val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    coroutineScope.launch {
        println("coroutineScope.launch : working in thread ${Thread.currentThread().name}")
    }
}